import threading
from typing import Callable, Optional

from src.core.activity_grabber import ActivityGrabber
from src.core.zhxy_client import ZhxyClient


class Qhd:
    def __init__(self, output: Callable = print):
        """
        初始化
        Args:
            output: 重定向输出函数
        """
        self.client = ZhxyClient()
        self.activity_grabber: Optional[ActivityGrabber] = None
        self._lock = threading.Lock()
        self._output = output

    def login(self, username: str, password: str) -> bool:
        """
        登陆
        Args:
            username: 学号
            password: 密码
        Returns:
            登陆成功返回True，否则返回False
        """
        self.safe_output('############ 开始登录 ############', "info")
        flag,msg = self.client.login(username, password)
        if flag:
            self.safe_output(msg, "success")
        else:
            self.safe_output(f"登陆失败：{msg}", "error")
        return flag

    def start_grab(self, activity_id: str, stop_callback: Callable = None) -> bool:
        """
        开始报名
        Args:
            activity_id: 活动id
            stop_callback: 停止回调函数
        Returns:
            开始成功返回True，否则返回False
        """
        with self._lock:
            if self.activity_grabber and self.activity_grabber.is_running:
                return False
            self.activity_grabber = ActivityGrabber(
                client=self.client, activity_id=activity_id,
                output=self._output, stop_callback=stop_callback
            )
            self.activity_grabber.start()
            return True

    def stop_grab(self) -> bool:
        """
        停止报名
        Returns:
            停止成功返回True，否则返回False
        """
        # 先获取锁，检查状态
        with self._lock:
            if not (self.activity_grabber and self.activity_grabber.is_running):
                return False
            # 保存引用
            grabber = self.activity_grabber
            self.activity_grabber = None

        # 在锁外调用 stop 方法，避免潜在的死锁
        grabber.stop()
        return True

    def safe_output(self, *args):
        """
        安全输出函数
        Args:
            *args: 输出内容
        """
        Qhd._func_exec(self._output, *args)

    @staticmethod
    def _func_exec(func: Callable, *args):
        """
        函数执行器，用于执行通过参数传递进来的函数
        Args:
            func: 函数
            *args: 参数
        """
        if func and callable(func):
            return func(*args)
        return None